var moment = require('moment');
var db = require('../config/mongo_database');
var tokenManager = require('../config/token_manager');
var sms = require('../route/sms');
var logger = require('../config/log4js').logger('access');


// 获取订单列表
exports.mylist = function(req, res){
	var userid = tokenManager.getUserId(req);
	db.orderModel.find({userid:userid, type:'0'}, 
		{userid:1,addr:1,orderid:1,pid:1,payAmount:1,post:1,express:1,score:1,cStatus:1,created:1,status:1},function (err, order) {
		logger.error(err);
		if(err || null==order)
			return res.sendStatus(403);
		return res.json(order);
	}).sort({ updated : -1 })
}

// 获取实物订单列表
exports.myslist = function(req, res){
	var userid = tokenManager.getUserId(req);
	db.orderModel.find({userid:userid, type:'2'}, 
		{userid:1,addr:1,orderid:1,pid:1,payAmount:1,post:1,express:1,score:1,cStatus:1,created:1,status:1},function (err, order) {
		logger.error(err);
		if(err || null==order)
			return res.sendStatus(403);
		return res.json(order);
	}).sort({ updated : -1 })
}

// 支付完更新订单
exports.payOrder = function(orderid, body){
	var pid = body.split('-')[0];
	var userid = body.split('-')[2];
	db.orderModel.findOne({orderid:orderid, status:'0'}, function(err, order){
		logger.error('payOrder',orderid, 'status:0', err);
		if(order){
			db.orderModel.update({orderid:orderid}, {$set:{status:'1', score:order.payAmount.toFixed(0), updated:new Date()}}, function(err){
				logger.info("支付成功更新订单状态：",orderid)
				logger.error("payOrder", err)
			})
			// 更新商品下载次数
			db.postModel.findOne({pid:pid}, function(err, post){
				logger.info("支付成功查询商品状态：",pid, err)
				if(post){
					post.times = post.times + 1;
					db.postModel.update({pid:pid}, {$set:{times:post.times, updated:new Date()}}, function(err){
						logger.info("支付成功更新商品次数：",pid, err)
					})
				}
			})
			// 更新用户积分
			db.userModel.findOne({_id:userid}, function (err, user) {
				if(user){
					user.score = Number(user.score) + Number(order.payAmount.toFixed(0))*2;
					console.log(user.score)
					db.userModel.update({_id:userid}, {$set:{score:user.score}}, function(err){
						logger.info("支付成功更新用户积分：",userid, err)
					})
					// 发送短信通知
					sms.send('13641892349', 1, [user.username, orderid])
					sms.send(user.username, 3, [orderid])
				}
			})
		}
	})
	
}

// 订单详情
exports.detail = function(req, res, next) {
	var params = req.query;
	var userid = tokenManager.getUserId(req);
	logger.info(params)
	db.orderModel.findOne({orderid:params.orderid, userid:userid}, function (err, order) {
		logger.error(err, order);
		if(err || null==order)
			return res.sendStatus(403);
		return res.json(order);
	})
}

// 生成实物订单
exports.snewOrder = function(req, res){
	var pid    = req.body.pid || '';
	var number = req.body.number || 1;
	var size   = req.body.size || null;
	var addr   = req.body.addr || null;
	var userid = tokenManager.getUserId(req);
	if(pid=='' || null==addr) return res.sendStatus(403);
	console.log(pid, number, size, addr)
	db.postModel.findOne({pid:pid}, function (err, post) {
		logger.error("snewOrder[postModel]: ", err)
		if(err || null==post){
			return res.sendStatus(403);
		}else{
			var order = new db.orderModel();
			order.userid = userid;
			order.orderid =   moment(new Date()).format("YYMMDD") + post.pid.substring(4) + tokenManager.getTimes(4);
			order.pid = post.pid;
			order.payAmount = post.price*number + post.yprice;
			order.type = '2';
			order.addr = addr;
			order.post = {codes:post.codes, price:post.price, yprice:post.yprice, name:post.name, type:post.type, number:number, size:size};
			order.save(function(err) {
				logger.error("newOrder[orderModel]: ", err)
				return res.json({orderid:order.orderid});
			})
		}
	})

}


// 生成订单
exports.newOrder = function(req, res, next) {
	var pid = req.body.pid || '';             // 商品号
	var userid = tokenManager.getUserId(req);
	if(pid=='') return res.sendStatus(403);
	
	db.postModel.findOne({pid:pid}, function (err, post) {
		logger.error("newOrder[postModel]: ", err)
		if(err || null==post){
			return res.sendStatus(403);
		}else{
			var order = new db.orderModel();
			order.userid = userid;
			order.orderid =   moment(new Date()).format("YYMMDD") + post.pid.substring(4) + tokenManager.getTimes(4);
			order.pid = post.pid;
			order.payAmount = post.price;
			order.post = {codes:post.codes, price:post.price, title:post.title, name:post.name, type:post.type, filename:post.download};
			order.save(function(err) {
				logger.error("newOrder[orderModel]: ", err)
				return res.json({orderid:order.orderid});
			})
		}
	})
}


// 根据商品生成保单
exports.getOrder = function(orderid, userid, callback){
	db.orderModel.findOne({orderid:orderid, userid:userid}, function (err, order) {
		logger.error("getOrder: ",err);
		if(err || null==order)
			return callback(false, null)
		return callback(true, order)
	})
}

// 取消订单
exports.cancelOrder = function(req, res, next){
	var orderid = req.query.orderid || '';
	var userid = tokenManager.getUserId(req);
	var whereData = {orderid:orderid, userid:userid, status:"0"};
	logger.info('cancelOrder:', whereData)
	db.orderModel.remove(whereData, function(err){ 
		return res.json({});
		// db.orderModel.find({userid:userid}, function (err, order) {
		// 	return res.json(order);
		// })
	})
}

// 更新订单信息，确认收货
exports.hasOk = function(req, res, next){
	var orderid = req.body.orderid || '';
	var userid = tokenManager.getUserId(req);
	var whereData = {orderid:orderid, userid:userid, status:"2"};
	logger.info('hasOk:', whereData)
	db.orderModel.update(whereData, {status:'3'}, function(err){ 
		if(err){
			logger.error(err)
			return res.sendStatus(403);
		}else
			return res.sendStatus(200);
	})
}
